class MyBlockingQueue {
    private String[] data = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    private Object locker = new Object();

    public MyBlockingQueue(int capacity) {
        data = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while (size == data.length) {
                // 队列满了
                locker.wait();
            }
            // 队列不满, 把元素放到 tail 所在的位置上
            data[tail] = elem;
            tail++;
            if (tail >= data.length) {
                tail = 0;
            }
            size++;
            locker.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (locker) {
            while (size == 0) {
                // 队列为空
                locker.wait();
            }
            String ret = data[head];
            head++;
            if (head >= data.length) {
                head = 0;
            }

            head = head % data.length;
            size--;
            // 通过这里的通知唤醒队列满的阻塞
            locker.notify();
            return ret;
        }
    }
}

public class Demo1 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(10);

        Thread producer = new Thread(() -> {
            try {
                int n = 1;
                while (true) {
                    queue.put(n + "");
                    System.out.println("生产元素: " + n);
                    n++;

                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                while (true) {
                    String result = queue.take();
                    System.out.println("消费元素: " + result);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        producer.start();
        consumer.start();
    }
}